package com.special.threademo.concurrency.lockDemo;

import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IDEA2020.3
 * author:LiuYC
 * DateTime:2021/1/15  14:44
 */
public class LockDemo {
    private Lock lock = new ReentrantLock(); // 可重入锁

    public void myMethod1() {
        try {
            lock.lock();
            System.out.println("mymythod1 invoked");
        } finally {
            lock.unlock();
        }
    }

    public void myMethod2() {
        try {
            lock.lock();
            System.out.println("mymythod2 invoked");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        LockDemo lockDemo = new LockDemo();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10; ++i) {
                lockDemo.myMethod1();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10; ++i) {
                lockDemo.myMethod2();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t1.start();
        t2.start();
    }
}
